//
//  VideosTableViewCell.m
//  XIWenLeJian
//
//  Created by lanou3g on 15/11/12.
//  Copyright © 2015年 蓝足. All rights reserved.
//

#import "VideosTableViewCell.h"
#import "VideoModel.h"
#import "UIImageView+WebCache.h"
#import "UIView+Extension.h"
#import "Masonry.h"
#import "JudgeMentInternet.h"
#import "UserInfo.h"
#import "DownLoadVideo.h"
#import "FileHandle.h"

#define leftEdge 20

@interface VideosTableViewCell ()<UserInfoDelegate>
// 判断是否下的对话框
@property (nonatomic, strong)UIAlertView *downLoad;
// 判断网络状态的对话框
@property (nonatomic, strong)UIAlertView *internet;

@end

@implementation VideosTableViewCell


- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    // 调用单例
    JudgeMentInternet *judgMent = [JudgeMentInternet defaultInstance];
    // 判断网络
    [judgMent changeInternet];
    
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // 标题
        _titleLabel = [[UILabel alloc]init];
        _titleLabel.frame = CGRectMake(leftEdge, 5, 300, 30);
        _titleLabel.numberOfLines = 0;
        _titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:13];

        [self.contentView addSubview:_titleLabel];


        // 收藏
        _collectBT = [[UIButton alloc]init];
        _collectBT.frame = CGRectMake(leftEdge + 315, 5, 23, 23);
        [_collectBT setImage:[UIImage imageNamed:@"iconfont-shoucang (1)"] forState:(UIControlStateNormal)];
        [_collectBT addTarget:self action:@selector(collect:) forControlEvents:(UIControlEventTouchUpInside)];
        [self.contentView addSubview:_collectBT];
    
    // 视频封面
        _cdn_img = [[UIImageView alloc]init];
        [self.contentView addSubview:_cdn_img];
        
        // 播放按钮
        _playBT = [[UIButton alloc]init];
        [_playBT addTarget:self action:@selector(play:) forControlEvents:(UIControlEventTouchUpInside)];
        [_playBT setBackgroundImage:[UIImage imageNamed:@"iconfont-bofang-1"] forState:(UIControlStateNormal)];
        [self.contentView addSubview:_playBT];
        
        // 视频时长
        _videotimeLabel = [[UILabel alloc]init];
        _videotimeLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:13];

        [self.contentView addSubview:_videotimeLabel];

        // 播放次数
        _playcountLabel = [[UILabel alloc]init];
        _playcountLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:13];

        [self.contentView addSubview:_playcountLabel];

    }
    return self;
}

// 给 model 赋值
- (void)setModel:(VideoModel *)model
{
    _model = model;
    
    // 收藏
    if (_model.isCollect) {
        [_collectBT setBackgroundImage:[UIImage imageNamed:@"iconfont-shoucang"] forState:(UIControlStateNormal)];
    }else{
        [_collectBT setBackgroundImage:[UIImage imageNamed:@"iconfont-shoucang (1)"] forState:(UIControlStateNormal)];
    }
    [_collectBT mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(- 5);
        make.top.mas_equalTo(8);
        make.size.mas_equalTo(CGSizeMake(30, 30));
    }];
    
    // 标题 , 发布时间
    // substringFromIndex表示从指定位置开始截取字符串到最后，所截取位置包含该指定位置。
    NSString *timeStr = [_model.created_at substringFromIndex:5];
    
    NSString *str = [NSString stringWithFormat:@"%@--%@", timeStr, model.text];
    _titleLabel.text = str;
    _titleLabel.textAlignment = NSTextAlignmentCenter;
    [_titleLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(leftEdge);
        make.top.mas_equalTo(8);
        make.right.mas_equalTo(-35);
        make.height.mas_equalTo(30);
    }];
    
    
    // 图片
    [self.cdn_img setImageWithURL:[NSURL URLWithString:model.image_small]];
    [_cdn_img mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(leftEdge);
        make.top.mas_equalTo(40);
        make.right.mas_equalTo(- 20);
        make.bottom.mas_equalTo(- 30);
    }];
    
    // 视频时长
    int time = [model.videotime intValue];
    int timeMin = time / 60;
    int timeSec = time % 60;
    if (timeSec < 10) {
        _videotimeLabel.text = [NSString stringWithFormat:@"时长%d :0%d", timeMin, timeSec + 1];
    }else{
        _videotimeLabel.text = [NSString stringWithFormat:@"时长%d :%d", timeMin, timeSec + 1];
    }
    [_videotimeLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(leftEdge);
        make.bottom.mas_equalTo(- 5);
        make.size.mas_equalTo(CGSizeMake(75, 20));
    }];
    
    // 播放次数
    _playcountLabel.text = [NSString stringWithFormat:@"播放次数:%ld", model.playcount];
    [_playcountLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(100);
        make.bottom.mas_equalTo(-5);
        make.size.mas_equalTo(CGSizeMake(100, 20));
    }];
    
    [_playBT mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(60, 60));
        make.center.equalTo(_cdn_img);
    }];
}

#pragma mark>>>>>>>>>>>>>>>>>收藏下载逻辑判断
// 收藏按钮的监听
- (void)collect:(UIButton *)bt
{
    DownLoadVideo *downloadVidoeSingle = [DownLoadVideo defaultInstance];
    if (![UserInfo shareUserInfo].isLogin) {
        self.loginBlock();
        [UserInfo shareUserInfo].delegate = self;
    }else{
        [self collected];
        if (_model.isCollect) {
            NSLog(@"进入下载");
            [self judgeDownLoadAlert];
        }else{
            //取消收藏/ 判断是否下载完毕 , 如果是就从沙盒删除
            if (downloadVidoeSingle.didDownLoad) {
                [self removeFile];
                downloadVidoeSingle.didDownLoad = NO;
                _model.isDownload = NO;
            }
            // 判断是否正在下载, 如果是就取消下载
            if (self.model.isDownload == 1) {
                [self cancelDownload];
                self.downloadBlock(@"NO");
                NSLog(@"取消下载");
            }else{
                self.reloadDataBlock();
            }
        }
    }
    _model.isCollect = !_model.isCollect;
    // 去执行block 的东西
    self.reloadDataBlock();
}

#pragma mark>>>>>>>>>>>>>>>>>userInfo 代理方法的实现
- (void)userInfo:(UserInfo *)userInfo select:(BOOL)isLogin
{
    [self collected];
    self.model.isCollect = NO;
}

// 播放按钮的监听
- (void)play:(UIButton *)bt
{
    self.movieBlock(_model.videouri);
}

- (void)collected
{
    _model.isCollect = !_model.isCollect;
    if (_model.isCollect) {
        NSDictionary *dic = @{
                              @"text":self.model.text, @"videouri":self.model.videouri, @"playcount":@(self.model.playcount), @"image_small":self.model.image_small , @"ID":@(self.model.ID),@"height":self.model.height,@"width":self.model.width,@"created_at":self.model.created_at
                              };
        [[FileHandle fileHandle]addVideoInFileDic:dic ID:_model.ID];
    }else{
        [[FileHandle fileHandle]removeVideoForID:_model.ID];
    }
}

#pragma mark>>>>>>>>>>>>>>> 提示框:判断是否下载 网络状态
- (void)judgeDownLoadAlert
{
    // 初始化 AlterView
    _downLoad = [[UIAlertView alloc]initWithTitle:@"收藏成功" message:@"是否将该视频下载到本地" delegate:self cancelButtonTitle:@"不用" otherButtonTitles:@"好的", nil];
}

// 判断网络状态及下载
// 根据被点击按钮的索引处理点击事件
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView == _downLoad) {
        // 调用网络单例
        JudgeMentInternet *judgeMent = [JudgeMentInternet defaultInstance];
        NSLog(@"下载的网络状态%@", judgeMent.status);
        // 对话框判断
        if (_internet == nil) {
            if (buttonIndex == 1) {
                if (judgeMent.isWifi) {
                    // 确认下载
                    self.model.isDownload = YES;
                    self.downloadBlock(_model.videouri);
                    // 接收返回视频的名字
                    [DownLoadVideo defaultInstance].pushName = ^(NSString *str){
                        self.model.videoName = str;
                    };
                }else{
                    [self judegeInternet:judgeMent.status];
                }
            }else{
                NSLog(@"第一个对话框取消");
                self.reloadDataBlock();
                self.model.isDownload = NO;
            }
        }else{
            self.internet = nil;
            if ([judgeMent.status isEqualToString:@"noInternet"]) {
                self.model.isDownload = NO;
            }else{
                if (buttonIndex == 1) {
                    NSLog(@"直接下载");
                    /// 直接返回视频的名字
                    [DownLoadVideo defaultInstance].pushName = ^(NSString *str){
                        self.model.videoName = str;
                    };
                    self.model.isCollect = YES;
                    self.downloadBlock(_model.videouri);
                    self.model.isDownload = YES;
                }else{
                    NSLog(@"不下载");
                }
            }
        }
    }else{
        NSLog(@"fuck");
    }
}

// 取消下载
- (void)cancelDownload
{
    // 初始化 alertView
    _internet = [[UIAlertView alloc]initWithTitle:@"取消收藏" message:@"下载任务取消" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
}

// 网络判断
- (void)judegeInternet:(NSString *)str
{
    NSString *message = [[NSString alloc]init];
    if ([str isEqualToString:@"data"]) {
        message = @"现在的网络状态为数据流量, 确定继续下载吗";
        // 初始化 alertView
        _internet = [[UIAlertView alloc]initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:@"谢谢不用" otherButtonTitles:@"下载", nil];
    }
    if ([str isEqualToString:@"noInternet"]) {
        message = @"没有网络连接, 请查看网络";
        // 初始化 alertView
        _internet = [[UIAlertView alloc]initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:@"稍后再试" otherButtonTitles:@"马上去设置网络", nil];
    }
    if ([str isEqualToString:@"unKnowInternet"]) {
        message = @"现在连接的网络为未知网络, 是否继续下载";
        // 初始化 alertView
        _internet = [[UIAlertView alloc]initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:@"谢谢不用" otherButtonTitles:@"下载", nil];
    }
    // 显示
    [_internet show];
}

#pragma mark>>>>>>>>>>>>>>>删除文件
- (void)removeFile
{
    NSFileManager *mgr = [NSFileManager defaultManager];
    //找到 caches 路径
    NSString *caches = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
    // 在 caches 后面拼接 video 路径
    NSString *videoStr = [caches stringByAppendingPathComponent:@"Video"];
    // 找到文件路径
    NSString *file = [videoStr stringByAppendingPathComponent:_model.videoName];
    [mgr removeItemAtPath:file error:nil];
}
- (void)awakeFromNib {
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
